package com.hou.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hou.eduservice.entity.EduSubject;
import com.hou.eduservice.entity.excel.SubjectData;
import com.hou.eduservice.service.EduSubjectService;
import lombok.SneakyThrows;

/**
 * @author shkstart
 * @create 2021-10-13-16:02
 */

// 不能交给spring管理
//  手动注入
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public EduSubjectService subjectService;

    public SubjectExcelListener(){

    }

    public SubjectExcelListener(EduSubjectService subjectService){
        this.subjectService = subjectService;
    }

    // 读取excel数据
    @SneakyThrows
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new Exception();
        }

        // 判断一级分类逻辑
        EduSubject subjectOne = this.exitOneSubject(subjectService, subjectData.getOneSubjectName());

        // 一级分类为空存储
        if (subjectOne == null) {
            subjectOne = new EduSubject();
            subjectOne.setParentId("0");
            subjectOne.setTitle(subjectData.getOneSubjectName());
            subjectService.save(subjectOne);
        }

        // 获取一级分类id
        String pid = subjectOne.getId();

        // 判断二级分类逻辑
        EduSubject subjectTwo = this.exitTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);

        // 二级分类为空存储
        if (subjectTwo == null){
            subjectTwo = new EduSubject();
            subjectTwo.setParentId(pid);
            subjectTwo.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(subjectTwo);
        }
    }

    // 判断一级分类不能重复添加
    private EduSubject exitOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<EduSubject>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id","0");
        EduSubject subject = subjectService.getOne(queryWrapper);
        return subject;
    }

    // 判断二级分类不能重复
    private EduSubject exitTwoSubject(EduSubjectService subjectService,String name, String pid){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<EduSubject>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",pid);
        EduSubject subject = subjectService.getOne(queryWrapper);
        return subject;
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
